package net.lab1024.sa.base.module.support.repeatsubmit.ticket;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import jakarta.servlet.http.HttpServletRequest;

import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 凭证（Caffeine实现）
 *
 * @Author 1024创新实验室-主任: 卓大
 * @Date 2025-07-26 23:56:58
 * @Wechat zhuoda1024
 * @Email lab1024@163.com
 * @Copyright <a href="https://1024lab.net">1024创新实验室</a>
 */
public class RepeatSubmitCaffeineTicket extends AbstractRepeatSubmitTicket {

    private final Cache<String, String> cache;

    public RepeatSubmitCaffeineTicket(Function<HttpServletRequest, String> ticketFunction) {
        super(ticketFunction);
        this.cache = Caffeine.newBuilder()
                .maximumSize(10000)
                .expireAfterWrite(1, TimeUnit.HOURS) // 默认1小时过期
                .build();
    }

    @Override
    public boolean tryLock(String ticket, Long currentTimestamp, Long intervalMilliSecond) {
        String existingValue = cache.getIfPresent(ticket);
        if (existingValue != null) {
            return false; // 已存在，获取锁失败
        }
        
        // 设置缓存
        if (intervalMilliSecond > 0) {
            // 创建带过期时间的缓存
            Cache<String, String> tempCache = Caffeine.newBuilder()
                    .maximumSize(10000)
                    .expireAfterWrite(intervalMilliSecond, TimeUnit.MILLISECONDS)
                    .build();
            tempCache.put(ticket, String.valueOf(currentTimestamp));
            // 将临时缓存的内容复制到主缓存
            cache.put(ticket, String.valueOf(currentTimestamp));
        } else {
            cache.put(ticket, String.valueOf(currentTimestamp));
        }
        
        return true;
    }

    @Override
    public void unLock(String ticket, Long intervalMilliSecond) {
        if (intervalMilliSecond > 0) {
            return; // 有过期时间的不需要手动删除
        }
        cache.invalidate(ticket);
    }
}